package com.relytosoft.mizar.media.host.emqx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.relytosoft.mizar.media.analyze.api.entity.system.AyGroupBase;
import com.relytosoft.mizar.media.analyze.api.entity.system.AyPersonGroup;
import com.relytosoft.mizar.media.analyze.services.service.system.AyGroupBaseService;
import com.relytosoft.mizar.media.analyze.services.service.system.AyPersonGroupService;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import com.relytosoft.mizar.media.common.entity.pojo.dto.FacePersonResDto;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * PersonDataMqttMessageListener
 *
 * @Author SunLi
 * @Date: 2022/5/31 14:33
 * @Version 1.0
 */
@Component
public class PersonDataMqttMessageListener implements com.relytosoft.mizar.media.common.emqx.listener.PersonDataMqttMessageListener {

    private static final Logger log = LoggerFactory.getLogger(FaceMqttMessageListener.class);

    @Resource
    private AyGroupBaseService ayGroupBaseService;

    @Resource
    private AyPersonGroupService ayPersonGroupService;


    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        if (topic.equals(MediaMqConstants.PERSON_DATA_TOPIC)) {
            boolean isConsume = false;
            String mqttMsg = new String(message.getPayload(), StandardCharsets.UTF_8);
            try {
                JSONObject jsonObject = JSON.parseObject(mqttMsg);
                String opType = jsonObject.getString("OpType");
                String data = jsonObject.getString("Data");
                switch (opType) {
                    //更新人脸库第三方ID
                    case "updateGroupId":
                        isConsume = updateGroupId(data);
                        break;
                    //更新人脸第三方ID
                    case "updatePersonId":
                        isConsume = updatePersonId(data);
                        break;
                    default:
                        break;
                }
                log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",接收的操作类型：" + opType + "，执行结果：" + isConsume);
            } catch (Exception e) {
                log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",处理发生错误：" + e.getMessage());
            }
        }
    }

    private boolean updateGroupId(String data) {
        Map<String, Object> map = JSONObject.parseObject(data, new TypeReference<Map<String, Object>>() {
        });
        //我们库的库ID
        Integer id = (Integer) map.get("id");
        //三方库的库ID
        String groupId = (String) map.get("groupId");
        //根据库id查询自己库信息并更新三方库ID到数据库
        AyGroupBase ayGroupBase = ayGroupBaseService.getById(id);
        ayGroupBase.setPlateformGroupId(groupId);
        return ayGroupBaseService.updateById(ayGroupBase);
    }


    private boolean updatePersonId(String data) {
        Map<String, Object> map = JSONObject.parseObject(data, new TypeReference<Map<String, Object>>() {
        });
        //自己系统人像ID
        Integer faceId = (Integer) map.get("faceId");
        //btdl返回人脸和库数据
        Object personInfos = map.get("personInfos");
        if (personInfos != null) {
            List<FacePersonResDto> dtoList = JSONObject.parseObject(JSONObject.toJSONString(personInfos), new TypeReference<List<FacePersonResDto>>() {
            });
            List<String> groupIds = dtoList.stream().map(FacePersonResDto::getGroupId).collect(Collectors.toList());
            Map<String, Integer> groupIdMap = ayGroupBaseService.selectPlateformAndGroupId(groupIds);
            Set<Integer> ownGroupIds = new HashSet<>(groupIdMap.values());
            //查询faceId和ownGroupIds的数据
            List<AyPersonGroup> ayPersonGroupList = ayPersonGroupService.selectAyPersonGroup(ownGroupIds, faceId);
            //封装数据
            for (FacePersonResDto facePersonResDto : dtoList) {
                for (AyPersonGroup ayPersonGroup : ayPersonGroupList) {
                    if (groupIdMap.get(facePersonResDto.getGroupId()).equals(ayPersonGroup.getGroupId())) {
                        ayPersonGroup.setPlatformPersonId(facePersonResDto.getPersonId());
                    }
                }
            }
            //批量更新
            return ayPersonGroupService.updateBatchById(ayPersonGroupList);
        }
        return false;
    }
}
